﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FF.Entity;
using FF.Method;
using System.IO;

namespace FF
{
    public partial class FormSaleManager : Form
    {
        public User user;
        public FormSaleManager(User user)
        {
            this.user = user;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void FormSaleManager_Load(object sender, EventArgs e)
        {
            checkBoxEnd.Checked = false;
            checkBoxStart.Checked = false;
            dateTimePickerStartday.Enabled = false;
            dateTimePickerEndday.Enabled = false;
        }

        private void buttonQuery_Click(object sender, EventArgs e)
        {
            //string sql = "SELECT order_id,customer_id,customer_name,user_id,user_name,good_id,good_name,good_num,good_price,receiver_name,total_prices,money_receive,discount,receive_company,strftime('%Y-%m-%d',add_date) as add_date,remark FROM ff_order where 1=1  ";
            string sql = "SELECT order_id,customer_id,customer_name,good_id,good_name,good_num,good_price,receiver_name,total_prices,money_receive,discount,receive_company,strftime('%Y-%m-%d',add_date) as add_date,remark FROM ff_order where 1=1  ";
            if(this.textBoxGoodid.Text.Trim() != "")
            {
                sql += " and good_id like '%" + this.textBoxGoodid.Text.Trim() +"%'";
            }
            if(this.textBoxGoodname.Text.Trim() != "")
            {
                sql += " and good_name like '%" + this.textBoxGoodname.Text.Trim() + "%'";
            }
            if(this.textBoxCustomerID.Text.Trim() != "")
            {
                sql += " and customer_id like '%" + this.textBoxCustomerID.Text.Trim() + "%'";
            }
            if (this.textBoxCustomername.Text.Trim() != "")
            {
                sql += " and customer_name like '%" + this.textBoxCustomername.Text.Trim() + "%'";
            }
            if(this.checkBoxStart.Checked)
            {
                sql += " and datetime(add_date) >=datetime('" + dateTimePickerStartday.Value.ToString("yyyy-MM-dd") + "')";
            }
            if(this.checkBoxEnd.Checked)
            {
                sql += " and datetime(add_date) <datetime('" + dateTimePickerEndday.Value.AddDays(1).ToString("yyyy-MM-dd") + "')";
            }

            try
            {
                DataSet ds = SQLiteHelper.Query(sql);
                dataGridView1.DataSource = ds.Tables[0];
                if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)
                {
                    MessageBox.Show("没有相关记录！", "提示信息 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //dataGridView1.DataSource = null;
                    return;
                }
                
                return;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("程序出错了！" + ex.Message, "提示信息 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string selectedId = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            Order order = OrderMethod.getEntityById(selectedId);

            if (order != null)
            {
                FormSale frm = new FormSale(this.user, selectedId);
                frm.Owner = this;
                frm.ShowDialog();
                buttonQuery_Click(sender, e);
            }
        }

        private void checkBoxStart_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePickerStartday.Enabled = (checkBoxStart.Checked ? true : false);
        }

        private void checkBoxEnd_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePickerEndday.Enabled = (checkBoxEnd.Checked ? true : false);
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = false;
            saveFileDialog.Title = "Export Excel File To";
            DateTime now = DateTime.Now;
            saveFileDialog.FileName = "销售信息"+now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');
            //saveFileDialog.ShowDialog();
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
           
            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                //写标题
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容
                for (int j = 0; j < dataGridView1.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridView1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        if (dataGridView1.Rows[j].Cells[k].Value != null)
                        tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                    }

                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("导出成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }          
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            DataGridView[] dataGridViews = { dataGridView1 };
            DataGridViewPrint print = new DataGridViewPrint(dataGridViews);
            print.Print();
        }
    }
}
